﻿using System;
using System.Net;
using System.Net.Sockets;

namespace Codemonk.Updater.Server
{
    public class SocketUpdateServer : IDisposable
    {
        private static Scheduler scheduler = new Scheduler();
        private int port = -1;
        private volatile bool isRunning = false;
        private IPEndPoint endPoint;
        public SocketUpdateServer(int port)
        {
            if (port < 0) throw new ArgumentException("port");
            this.port = port;
            endPoint = new IPEndPoint(IPAddress.Loopback, port);
        }

        public void Start()
        {
            if (isRunning) return;
            isRunning = true;
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Bind(endPoint);
                socket.Listen(128);
                while (isRunning)
                {
                    var client = socket.Accept();
                    scheduler.AddClient(new SocketClient { Client = client });
                    System.Threading.Thread.Sleep(0);
                }
            }
        }

        public void Dispose()
        {
            isRunning = false;
        }
    }
}
